package com.kun.portal.webframe.service;

import com.kun.framework.core.util.SimpleKey;
import com.kun.portal.webframe.dao.DeptMgrDao;
import com.kun.portal.webframe.po.DeptMgrPo;
import com.kun.portal.webframe.po.FwModulePo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.util.List;

/**
 * Created by Administrator on 2018/5/21.
 */
@Service
public class DeptMgrService {
    @Autowired
    private DeptMgrDao deptMgrDao;
    @Autowired
    private EntityManager entityManager;

    public List<DeptMgrPo> findByParentCode(String val1){
        return deptMgrDao.findByParentCode(val1);
    }

    public DeptMgrPo addDept(DeptMgrPo deptMgr) {
            DeptMgrPo deptMgrPo = (DeptMgrPo) this.deptMgrDao.save(this.createDeptCode(deptMgr));
        return deptMgrPo;
    }
    private DeptMgrPo createDeptCode(DeptMgrPo deptMgr) {
        String deptCode = StringUtils.isNoneBlank(new CharSequence[]{deptMgr.getDeptCode()})?deptMgr.getDeptCode(): SimpleKey.genShortUuid();
        if(StringUtils.isNoneBlank(new CharSequence[]{deptMgr.getParentCode()})) {
            deptMgr.setDeptCode(deptMgr.getParentCode() + "-" + deptCode);
        } else {
            deptMgr.setDeptCode(deptCode);
        }

        return deptMgr;
    }
    public String findMaxDeptCodeByParentCode(String parentCode) {
        Query query;
        if(parentCode == null) {
            query = this.entityManager.createNativeQuery("select max(dept_code) from dept_mgr where parent_code is null");
            return (String)query.getSingleResult();
        } else {
            query = this.entityManager.createNativeQuery("select max(dept_code) from dept_mgr where parent_code = ?1");
            query.setParameter(1, parentCode);
            return (String)query.getSingleResult();
        }
    }

    public DeptMgrPo updateDept(DeptMgrPo deptMgr) {
       DeptMgrPo deptMgrPo = (DeptMgrPo) this.deptMgrDao.save(deptMgr);
        return deptMgrPo;
    }
    @Transactional
    public void deleteDeptMgr(String deptId) {
        List<DeptMgrPo> deptMgrPos = this.deptMgrDao.findChildrenByDeptId(deptId);
        this.deptMgrDao.delete(deptMgrPos);
        this.deptMgrDao.delete(deptId);
    }



}
